﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using eTMS.Controllers.HoSoService;
using eTMS.Controllers;
using eTMS.Commons;
using eTMS.Controls;

namespace eTMS.Forms.ManageList
{
    public partial class FrmHoSo  : eTMS.Controls.BaseForm
    {
        public FrmHoSo()
        {
            InitializeComponent();
        }
        #region Variables
        private HoSoController controller = new HoSoController();
        #endregion
        #region Screen Functions
        //Load All lable text
        private void LoadLanguage()
        {
            this.Text = HoSoStringMapping.HoSo;
            this.labelFormTitle.Text = Constants.APP_ADMINISTRATION + " " + HoSoStringMapping.HoSo;
            this.groupBoxDetail.Text = Constants.APP_DETAIL;
            this.groupBoxList.Text = Constants.APP_LIST;
            this.ColumnSTT.HeaderText = Constants.APP_INDEX;
            labelMaHoSo.Text = HoSoStringMapping.MaHoSo;
            ColumnMaHoSo.HeaderText = HoSoStringMapping.MaHoSo;
            labelTenHoSo.Text = HoSoStringMapping.TenHoSo;
            ColumnTenHoSo.HeaderText = HoSoStringMapping.TenHoSo;
            labelMoTaHoSo.Text = HoSoStringMapping.MoTaHoSo;
            ColumnMoTaHoSo.HeaderText = HoSoStringMapping.MoTaHoSo;
            labelNopKhiNhapHoc.Text = HoSoStringMapping.NopKhiNhapHoc;
            ColumnNopKhiNhapHoc.HeaderText = HoSoStringMapping.NopKhiNhapHoc;
            labelLoaiGiayTo.Text = LoaiGiayToStringMapping.LoaiGiayTo;
        }
        //Get entity selected from datagrid
        private HoSoEntity GetObject()
        {
            HoSoEntity o = controller.MapDataRowToObject(((DataRowView)gridData.SelectedRows[0].DataBoundItem).Row);
            controller.HoSoObject = o;
            return o;
        }
        //Get entites selected from datagrid
        private List<DataRow> GetSelectedDataRows()
        {
            List<DataRow> ls = new List<DataRow>();
            for (int i = 0; i < gridData.SelectedRows.Count; i++)
            {
                ls.Add(GetDataRow(gridData.SelectedRows[i].Index));
            }
            return ls;
        }
        //Get the selected data row in datagrid
        private DataRow GetSelectedDataRow()
        {
            DataRow row = GetDataRow(gridData.SelectedRows[0].Index);
            return row;
        }
        //Get the selected data row in datagrid
        private DataRow GetDataRow(int index)
        {
            DataRow row = ((DataRowView)gridData.Rows[index].DataBoundItem).Row;
            return row;
        }
        //Reset all textbox
        private void ClearScreen()
        {
            txtMaHoSo.Text = "";
            txtTenHoSo.Text = "";
            txtMoTaHoSo.Text = "";
            controller.InitTableDetail();
            gridDetail.AutoGenerateColumns = false;
            gridDetail.DataSource = controller.tblDataDetail;
            errorProviderData.Clear();
        }
        //Lock-Unlock control in screen
        private void LockScreen(bool IsLocked)
        {
            ucCommand.LockControl(IsLocked);
            txtMaHoSo.ReadOnly = IsLocked;
            txtTenHoSo.ReadOnly = IsLocked;
            txtMoTaHoSo.ReadOnly = IsLocked;
            txtNopKhiNhapHoc.Enabled = !IsLocked;
            gridDetail.ReadOnly =IsLocked;
            btnAddDetail.Enabled = !IsLocked;
            btnRemoveDetail.Enabled = !IsLocked;
        }
        //Copy data from control in screen to object
        private void CopyFromSreen(HoSoEntity o)
        {
            o.MaHoSo = Convert.ToString(txtMaHoSo.Text);
            o.TenHoSo = Convert.ToString(txtTenHoSo.Text);
            o.MoTaHoSo = Convert.ToString(txtMoTaHoSo.Text);
            o.NopKhiNhapHoc = txtNopKhiNhapHoc.Checked;
        }
        //Bind data from object to control in screen
        private void CopyToSreen(HoSoEntity o)
        {
            if (!o.IsNullMaHoSo)
            {
                txtMaHoSo.Text = Convert.ToString(o.MaHoSo);
            }
            if (!o.IsNullTenHoSo)
            {
                txtTenHoSo.Text = Convert.ToString(o.TenHoSo);
            }
            if (!o.IsNullMoTaHoSo)
            {
                txtMoTaHoSo.Text = Convert.ToString(o.MoTaHoSo);
            }
            if (!o.IsNullNopKhiNhapHoc)
            {
                txtNopKhiNhapHoc.Checked = o.NopKhiNhapHoc;
            }
        }
        //Validate all data from control in screen before Save data
        protected bool ValidateScreen()
        {
            bool result = true;
            if (txtMaHoSo.Text.Trim() == "")
            {
                txtMaHoSo.Focus();
                errorProviderData.SetError(txtMaHoSo, Constants.MSS_ERROR_TEXT);
                result = false;
            }
            else
            {
                errorProviderData.SetError(txtMaHoSo, "");
            }
            if (txtTenHoSo.Text.Trim() == "")
            {
                txtTenHoSo.Focus();
                errorProviderData.SetError(txtTenHoSo, Constants.MSS_ERROR_TEXT);
                result = false;
            }
            else
            {
                errorProviderData.SetError(txtTenHoSo, "");
            }
            if (!result)
            {
                ShowInfo(Constants.MSS_REQUIRE_FIELD);
            }
            if (result)
            {
                //Check if exists MaHoSo				
                bool existsMaHoSo = controller.CheckExistsMaHoSo(txtMaHoSo.Text);
                bool editexists = false;
                if (Flag == ACTIONENUM.Edit)
                {
                    DataRow row = GetSelectedDataRow();
                    string newVal = txtMaHoSo.Text;
                    editexists = Convert.ToString(row["MaHoSo"]) != Convert.ToString(newVal);
                }
                if (existsMaHoSo && ((Flag == ACTIONENUM.AddNew) || editexists))
                {
                    result = false;
                    errorProviderData.SetError(txtMaHoSo, Constants.MSS_ERROR_DATA_UNIQUE);
                    txtMaHoSo.Focus();
                    ShowInfo(Constants.MSS_ERROR_EXISTS_DATA);
                }
                else
                {
                    errorProviderData.SetError(txtMaHoSo, "");
                }
            }
            return result;
        }
        //Copy data from selected object to control in screen
        private void BindInfo()
        {
            if (gridData.SelectedRows.Count == 0) return;
            if (gridData.SelectedRows[0].Index < gridData.Rows.Count)
            {
                HoSoEntity o = GetObject();
                CopyToSreen(o);
                BindDetails();
            }
        }
        #endregion
        #region Business
        //AddNew data to database
        private bool AddNewData()
        {
            bool rval = false;
            controller.ResetObject();
            CopyFromSreen(controller.HoSoObject);
            rval = controller.AddNew();
            if (rval)
            {
                controller.SaveDetail();
                DataRow row = controller.Table.NewRow();
                row["STT"] = controller.Table.Rows.Count + 1;
                controller.MapObjectToDataRow(row);
                controller.Table.Rows.Add(row);
                gridData.DataSource = null;
                gridData.DataSource = controller.Table;
            }
            return rval;
        }
        //Update data to database
        private bool UpdateData()
        {
            DataRow row = GetSelectedDataRow();
            controller.LoadObject((Int32)row["HoSo_ID"]);
            CopyFromSreen(controller.HoSoObject);
            bool rval = controller.Update();
            if (rval)
            {
                controller.SaveDetail();
                controller.MapObjectToDataRow(row);
                gridData.InvalidateRow(gridData.SelectedRows[0].Index);
            }
            return rval;
        }
        //Delete data from database
        private bool DeleteData()
        {
            List<DataRow> ls = GetSelectedDataRows();
            if (ls.Count == 0) return false;
            bool rval = true;
            try
            {
                gridData.DataSource = null;
                foreach (DataRow row in ls)
                {
                    if (controller.DeleteByID((Int32)row["HoSo_ID"]))
                    {
                        this.controller.Table.Rows.Remove(row);
                    }
                    else
                    {
                        rval = false;
                    }
                }
                this.controller.ResetTableIndex();
                gridData.DataSource = this.controller.Table;
            }
            catch
            {
                return false;
            }
            return true;
        }
        #endregion
        #region DataBinding
        //Bind data to datagrid
        private void LoadData()
        {
            gridData.AutoGenerateColumns = false;
            gridData.DataSource = controller.Table;
            gridData.AutoResizeColumns();
        }
        #endregion
        #region Windows Control EventHandlers
        private void FrmHoSo_Load(object sender, EventArgs e)
        {
            LoadLanguage();
            LoadData();
            LockScreen(true);
        }
        private void BindDetails()
        {
            controller.LoadDataChiTiet();
            gridDetail.AutoGenerateColumns = false;
            gridDetail.DataSource = controller.tblDataDetail;
        }
        private void gridData_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            BindInfo();
        }
        private void ucCommand_OnAddNew(object sender, EventArgs e)
        {
            ClearScreen();
            LockScreen(false);
            Flag = ACTIONENUM.AddNew;
            txtMaHoSo.Focus();
        }
        private void ucCommand_OnDelete(object sender, EventArgs e)
        {
            if (gridData.SelectedRows.Count == 0)
            {
                ShowInfo(Constants.MSS_CHOOSERECORD_REQUIRE);
                return;
            }
            if (!Confirm(Constants.MSS_CONFIRM_DELETE)) return;
            DeleteData();
            this.gridData.Focus();
        }
        private void ucCommand_OnEdit(object sender, EventArgs e)
        {
            if (gridData.SelectedRows.Count == 0)
            {
                ShowInfo(Constants.MSS_CHOOSERECORD_REQUIRE);
                return;
            }
            LockScreen(false);
            Flag = ACTIONENUM.Edit;
            txtMaHoSo.Focus();
        }
        private void ucCommand_OnSave(object sender, EventArgs e)
        {
            if (!ValidateScreen())
                return;
            if (Flag == ACTIONENUM.Edit)
            {
                if (UpdateData())
                {
                    ShowInfo(Constants.MSS_SAVE_SUCCESS);
                }
                else
                {
                    ShowWarning(Constants.MSS_SAVE_FAILE);
                }
                gridData.Focus();
            }
            else
            {
                if (AddNewData())
                {
                    ShowInfo(Constants.MSS_SAVE_SUCCESS);
                }
                else
                {
                    ShowWarning(Constants.MSS_SAVE_FAILE);
                }
            }
            LockScreen(true);
            Flag = ACTIONENUM.None;
        }
        private void ucCommand_OnSkip(object sender, EventArgs e)
        {
            LockScreen(true);
            if (Flag == ACTIONENUM.AddNew)
            {
                ClearScreen();
                ucCommand.SetFocusAddNew();
            }
            else if (Flag == ACTIONENUM.Edit)
            {
                BindInfo();
                this.gridData.Focus();
            }
            Flag = ACTIONENUM.None;
        }
        #endregion

        private void btnAddDetail_Click(object sender, EventArgs e)
        {
            FrmChooseLoaiGiay frmChooseLoaiGiay = new FrmChooseLoaiGiay();
            frmChooseLoaiGiay.ListLoaiGiayToInvisibled = controller.GetListLoaiGiayTo();
            if (frmChooseLoaiGiay.ShowDialog() == DialogResult.OK)
            {
                controller.AddLoaiGiayTo(frmChooseLoaiGiay.ListCheckedLoaiGiayTo);
            }
        }

        private void btnRemoveDetail_Click(object sender, EventArgs e)
        {
            if ((gridDetail.SelectedRows.Count == 0) || (gridDetail.SelectedCells.Count == 0)) return;
            if (!Confirm("Bạn thực sự muốn loại bỏ các loại giấy tờ đã chọn ra khỏi hồ sơ?")) return;
            List<int> lsRowIndex = new List<int>();
            foreach (DataGridViewRow row in gridDetail.SelectedRows)
            {
                lsRowIndex.Add(row.Index);
            }
            foreach (DataGridViewCell cell in gridDetail.SelectedCells)
            {
                if (!lsRowIndex.Contains(cell.RowIndex))
                    lsRowIndex.Add(cell.RowIndex);
            }
            List<DataRow> lsSelectedRow = new List<DataRow>();
            foreach (int index in lsRowIndex)
            {
                lsSelectedRow.Add(((DataRowView)gridDetail.Rows[index].DataBoundItem).Row);
            }
            controller.RemoveLoaiGiayTo(lsSelectedRow);
        }
    }
}
